/*
 * DO NOT  start this server.  must be called from main server
 * 
 * 不能单独启动web服务， 必须从主服务器调用 
 */
import express = require('express');
import common from '../middleware/WebCommon';
import constant from '../common/WebConstant';
import WebServer from '../middleware/WebServer';

import AjaxPage from '../controller/AjaxDataProvider';
import pagedata from '../controller/AdminLogicClass';
import UploadUtil, { UploadResult } from '../middleware/UploadUtil';

import WebReq = express.Request;
import WebRes = express.Response;
import WebConstant from '../common/WebConstant';
import CommonFunc from '../middleware/CommonFunc';

export default class AdminServer extends WebServer {
    public startServer(port:number) {
        super.start(port,"0.0.0.0");

        UploadUtil.connectTask();
    }
    protected initroute(){
        let _this = this;
        let ajax = new AjaxPage();
        super.addRoutePath("/", "get", function (req:WebReq, res:WebRes) {  
            // var ipLegal = Func.checkClientIP(req);
            // if(!ipLegal) {
            //     res.render('500',{constant:constant, errormsg:"IP地址不在白名单中，拒绝访问"});
            //     return;
            // }
            if(req.session && req.session.user){
              var username = req.session && req.session.user && req.session.user.username || '';
              let page:any = new pagedata();
              var promise = page["index"](req);
                promise.then(function(result:any){
                    var pager = result.pager || {};
                    res.render("index",{"constant":constant,"username":username,"pager":pager, "data":result.data,"param":result.param});
                });
            }
            else{
              res.render('login',{constant:constant});
            } 
        });
        super.addRoutePath('/logout','get',function(req:WebReq, res:WebRes){
            if(req.session ){
                delete req.session.user 
            };
            res.redirect('/')
        });
        super.addRoutePath('/*.html','get', function(req:WebReq, res:WebRes) {
            _this.pageHandler(req, res,"");
        });
        super.addRoutePath('/logincheck','post', function(req:WebReq, res:WebRes) {
            let promise = ajax.login(req);
            promise.then(function(data:any){
                res.json(data);
            });
        });
        super.addRoutePath('/file-upload','post', function(req:WebReq, res:WebRes) {
            if(req.session && req.session.user){
                var username = req.session && req.session.user && req.session.user.username || '';
                UploadUtil.uploadFile(req, res, username).then((ret:UploadResult)=>{
                    if(ret.success){
                        res.json({});
                    }
                    else{
                        res.json({"code":500,"error":ret.msg});
                    }
                });
            }
            else{
                res.json({"code":500,"error":"请先登录"});
            }
        });
        super.addRoutePath('/ajax/*','post', function(req:WebReq, res:WebRes) {
            if(req.session && !req.session.user){
                res.json({"success":false,"error":"还没有登录"});
                return;
            }

            var action = req.params[0];
            if(typeof(ajax[action+""]) == "function"){
                 let promise = ajax[action+""](req);
                 
                 promise.then(function(ret:any){
                    if(ret != undefined){
                        res.json(ret);
                    }else{
                        res.json({"success":false,"error":"[500]请求失败"});
                    }
                });
            }
            else{
                res.json({"success":false,"error":"[404]请求的地址不存在"});
            }
        });
        super.addRoutePath('/showpic', 'get', function(req:WebReq, res:WebRes) {
            if(!req.query || !req.query.path){
                res.json({"success":false,"error":"参数不正确"});
                return;
            }
            let currentUser = req.session && req.session.user && req.session.user.username;

            let defaultPath = CommonFunc.getRootUserPath(currentUser);
            let path = req.query.path;
            res.redirect(WebConstant.SITE_ROOT+defaultPath+path);
        });
    }
    //处理页面请求
    private pageHandler(req:express.Request, res:express.Response, viewpath:string) {
        if(req.session && !req.session.user){
            //req.session.user = {"username":"admin"}; //TODO: 本地测试代码，部署时一定要去掉
            return res.redirect('/');
        }else{
            var actionname = req.params[0];
            var filename = viewpath + actionname;
            common.checkTempFile(filename, function(rsp){
                if(rsp){
                    var username = req.session && req.session.user && req.session.user.username || '';
                    //console.log(username);
                    let page:any = new pagedata();
                    
                    if(typeof(page[""+actionname]) != "function"){
                        res.render(filename,{"constant":constant,"username":username});
                        return;
                    }
     
                    var promise = page[""+actionname](req);
                    promise.then(function(result:any){
                        var pager = result.pager || {};
                        res.render(filename,{"constant":constant,"username":username,"pager":pager, "data":result.data,"param":result.param});
                    });
                    
                }
                else{
                    res.render('404',{"constant":constant});
                }
            });
        }
    }
}

 